package com.lichao.cdc;

/**
 * @author: li chao
 * @Desc:
 * @create: 2024-07-17 09:35
 **/

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SQLConditionParser {


    public static Map<String, String> parseSQLConditionsToMap(String sql) {
        // 简化正则表达式，假设所有条件都是“字段名 = 值”的形式，并且用AND连接
        // 注意：这个正则表达式不处理引号内的空格、转义字符等复杂情况
        String regex = "(\\w+)\\s*=\\s*('[^']+'|[^']+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql);

        Map<String, String> conditions = new HashMap<>();

        while (matcher.find()) {
            // 捕获组1是字段名，捕获组2是值（去除了引号）
            String fieldName = matcher.group(1);
            String valueWithQuotes = matcher.group(2);
            // 去除值两边的引号
            String value = valueWithQuotes.startsWith("'") && valueWithQuotes.endsWith("'") ?
                    valueWithQuotes.substring(1, valueWithQuotes.length() - 1) :
                    valueWithQuotes;
            conditions.put(fieldName, value);
        }

        return conditions;
    }

    public static void main(String[] args) {
        String sql = "Price = 79 and Source= 'Shipping'";
        Map<String, String> result = parseSQLConditionsToMap(sql);

        // 打印结果
        for (Map.Entry<String, String> entry : result.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }

}